from flask import g
from comment.modules.user import User
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules import db
from comment.modules.product import Product
from comment.modules.invest_record import Invest_record
from comment.modules.deal_record import DealRecord
from comment.utils.decrators import login_required
from financial.resource.transaction.serializers import InvestRecordPaginateSerializer,DealRecordPaginateSerializer


class Deal_Reource(Resource):
    '''交易记录资源类'''

    def get(self):
        '''交易记录的列表'''

        rp =RequestParser()
        rp.add_argument('start')  #起始时间
        rp.add_argument('end')  #结束时间
        rp.add_argument('deal_type')  #交易类型  0代表全部
        rp.add_argument('curPage',required=True)  #当前页号
        rp.add_argument('per_page',required=True)  #每页的显示行数

        args = rp.parse_args()
        start = args.get('start')
        end = args.get('end')
        deal_type = 0 if args.get('deal_type') == None else int(args.get('deal_type'))
        cur_page = int(args.get('curPage'))
        page_size = int(args.get('per_page'))

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        #得到一个查询对象
        q = DealRecord.query
        #第一个过滤，根据交易类型过滤
        if deal_type > 0:
            q = q.filter(DealRecord.aType == deal_type)
        # 第二个过滤： 根据用户ID (当前用户如果是管理员，可以查询所有的，否则只能查询自己的)
        if user.role == 0:
            q = q.filter(DealRecord.aUserId == user_id)

        # 第三次过滤，根据起始时间过滤
        if start and end:
            q = q.filter(db.cast(DealRecord.aDate, db.DATE) >= db.cast(start, db.DATE)) \
                .filter(db.cast(DealRecord.aDate, db.DATE) <= db.cast(end, db.DATE))

        data = q.paginate(cur_page, page_size, error_out=False)
        data = DealRecordPaginateSerializer(data).to_dict()

        return {'msg':'Success !!','data':data}